package com.zcx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcx.pojo.Menu;
import com.zcx.mapper.MenuMapper;
import com.zcx.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  菜单实现层
 * </p>
 *
 * @author zcx
 * @since 2022-03-31
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    MenuMapper menuMapper;
    /**
    　* @author zhaochangxin
    　* @Description:查询所有菜单
    　* @return: java.util.List<com.zcx.pojo.Menu>
    　* @date 2022/3/31 17:13
    　* @throws
    　*/
    @Override
    public List<Menu> queryAllMenu() {
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
        List<Menu> EndMenu = new ArrayList<>();
        // 查询到父菜单
        menuQueryWrapper.eq("parent_id","0");
        List<Menu> RootMenu = menuMapper.selectList(menuQueryWrapper);
        // 查询所有除父菜单之外的菜单
        menuQueryWrapper.clear();
        menuQueryWrapper.ne("parent_id","0");
        List<Menu> menusListNeRoot = menuMapper.selectList(menuQueryWrapper);
        // 去遍历父菜单 将父菜单和所有菜单比较 如果有菜单的parent_id==他的id 就将他添加为children
        for (Menu menu : RootMenu) {
            //查询子菜单 递归方法
            EndMenu.add(getChildrenList(menu, menusListNeRoot));
        }
        return EndMenu;
    }
    /**
    　* @author zhaochangxin
    　* @Description:将父菜单和所有菜单比较 如果有菜单的parent_id==他的id 就将他添加为children
    　* @Param childMenu: 父菜单
     * @Param menuChildrenList: 所有除了父菜单的菜单
    　* @return: com.zcx.pojo.Menu
    　* @date 2022/3/31 17:11
    　*/
    public Menu getChildrenList(Menu RootMenu, List<Menu> menuChildrenList) {
        for (Menu menu : menuChildrenList) {
            if (RootMenu.getId().equals(menu.getParentId())){
                RootMenu.getChildren().add(getChildrenList(menu, menuChildrenList));
            }
        }
        return RootMenu;
    }
}
